<!--
 * @Description: 
 * @Author: qingyang
 * @Date: 2023-07-24 15:02:09
 * @LastEditors: qingyang
 * @LastEditTime: 2023-07-26 17:25:33
-->
<template>
  <CDialog
    title="关联因子库"
    v-model:visible="dialogVisible"
    :footer="false"
    size="auto"
    :contentHeader="48"
  >
    <template #contentHeader>
      <div class="header">
        <div>
          <el-input
            class="header-input search-bar-item"
            placeholder="因子编号或名称"
            v-model="searchForm.factorNameOrNo"
            clearable
          >
          </el-input>
          <GSelect placeholder="因子类别" v-model="searchForm.category" clearable>
            <el-option
              v-for="item in FactorCategoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </GSelect>
          <el-input
            class="header-input search-bar-item"
            placeholder="国别（地区）"
            v-model="searchForm.country"
            clearable
          >
          </el-input>
          <GSelect placeholder="因子来源" v-model="searchForm.factorSource" clearable>
            <el-option
              v-for="item in FactorSourceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </GSelect>
          <el-input
            class="header-input search-bar-item"
            placeholder="因子标签"
            v-model="searchForm.tag"
            clearable
          >
          </el-input>
        </div>
        <div id="factor-simple-page"></div>
      </div>
    </template>

    <CTable
      :pagination="{
        teleport: '#factor-simple-page',
        layout: 'total, prev, slot, next'
      }"
      :loadData="loadData"
      ref="tableRef"
      @cell-dblclick="handleDbclick"
    >
      <vxe-column title="因子名称/英文名称/因子编号" min-width="200">
        <template #default="scope">
          <CTableColumn :main-text="scope.row.factorName" :sub-text="empty(scope.row.enName)">
            <template #third>
              <p class="g-font-12n3">{{ empty(scope.row.factorNo) }}</p>
            </template>
          </CTableColumn>
        </template>
      </vxe-column>
      <vxe-column title="因子类别/国别" min-width="100">
        <template #default="scope">
          <CTableColumn
            :main-text="FactorCategoryMap[scope.row.category]"
            :sub-text="scope.row.country"
          ></CTableColumn>
        </template>
      </vxe-column>
      <vxe-column title="碳排放因子/因子来源" width="250">
        <template #default="scope">
          <CTableColumn
            :main-text="`${scope.row.emissionFactor}${handleUnit(scope.row.factorUnit)}`"
            :sub-text="FactorSourceMap[scope.row.factorSource]"
          ></CTableColumn>
        </template>
      </vxe-column>
      <vxe-column title="基准年" width="70">
        <template #default="scope">
          {{ empty(scope.row.baseYear) }}
        </template>
      </vxe-column>
      <vxe-column title="因子标签" min-width="150">
        <template #default="scope">
          <div class="model-tag-wrap" v-if="scope.row.tag">
            <div
              class="model-tag"
              v-for="(item, index) in renderTags(scope.row.tag)"
              :key="index"
              >{{ item }}</div
            >
          </div>
          <span v-else>-</span>
        </template>
      </vxe-column>
      <vxe-column title="备注" min-width="150">
        <template #default="scope">
          <p v-ellTooltip:2>{{ empty(scope.row.comment) }}</p>
        </template>
      </vxe-column>
      <vxe-column title="操作" width="80">
        <template #default="scope">
          <el-button :loading="addLoading" type="primary" text @click="handleClick(scope.row)"
            >关联</el-button
          >
        </template>
      </vxe-column>
    </CTable>
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'CFootprintFactorDrawer'
};
</script>
<script lang="ts" setup>
import { withDefaults, defineProps, computed, defineEmits, ref, watch } from 'vue';
import { CTable } from '@/components/CTable/index';
import { useFactorList } from './useFactorDialog';
import { empty } from '@/utils/index';
import { GSelect } from '@/components/GSelect/index';
import { CTableColumn } from '@/components/CTable';
import { FactorCategoryOptions, FactorSourceOptions } from '@/constants/enum';
import { RelationBatchFactorParams } from '@/apis/pcf/myModel/model/modelManage';
import { useMessage } from '@/hooks/useMessage';
import { relationBatchFactor } from '@/apis/pcf/myModel/modelList';
import { CDialog } from '@/components/CDialog';
import { RelationFactorListResult } from '@/apis/pcf/myModel/model/modelDetailModel';
import { FactorSourceMap, FactorCategoryMap } from '@/constants/enum';
interface IDialogProps {
  visible: boolean;
  modelNo?: string;
  nodeNoList?: string[];
}
const { createMessage } = useMessage();

const props = withDefaults(defineProps<IDialogProps>(), {
  nodeNoList: () => []
});
const emit = defineEmits(['update:visible', 'finish']);
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
const { loadData, searchForm, tableRef } = useFactorList();
watch(
  () => dialogVisible.value,
  val => {
    searchForm.factorNameOrNo = undefined;
    searchForm.category = undefined;
    searchForm.factorSource = undefined;
    searchForm.country = undefined;
    searchForm.tag = undefined;
  }
);
const addLoading = ref(false);
const handleClick = (row: any) => {
  if (!props.modelNo) {
    dialogVisible.value = false;
    const selectedFactor = {
      factorNo: row.factorNo,
      factorName: row.factorName,
      emissionFactor: row.emissionFactor,
      factorUnit: row.factorUnit
    };
    emit('finish', selectedFactor);
    return;
  }
  addLoading.value = true;
  const params: RelationBatchFactorParams = {
    modelNo: props.modelNo,
    nodeNoList: props.nodeNoList,
    factorNo: row.factorNo
  };

  relationBatchFactor(params)
    .then(() => {
      createMessage.success('关联成功');
      dialogVisible.value = false;
      emit('finish');
    })
    .finally(() => {
      addLoading.value = false;
    });
  dialogVisible.value = false;
};
const handleDbclick = ({ row }: { row: RelationFactorListResult }) => {
  handleClick(row);
};

const renderTags = (tag: string) => {
  if (tag) {
    return tag.split(',');
  }
  return [];
};
// 处理表内的单位换成标准格式
const handleUnit = (factorUnit: string) => {
  //  eg: factorUnit:'kg CO₂e/m3'
  if (factorUnit.includes('/')) {
    let unit = factorUnit.split('/');
    return `kg CO₂e/${unit[1]}`;
  } else if (factorUnit) {
    return factorUnit;
  } else {
    return '';
  }
};
</script>

<style lang="scss" scoped>
.header {
  padding: 0 24px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  :deep(.el-select) {
    width: 128px;
    margin-right: 10px;
  }
  .header-unit {
    width: 128px;
    margin: 0 10px;
  }
  .header-input {
    width: 192px;
    margin-right: 10px;
  }
}
.search-bar-item {
  height: 32px !important;
  .el-input__wrapper {
    height: 32px;
  }
  .el-input__inner {
    height: 32px;
  }
}
.model-tag {
  min-width: 36px;
  height: 20px;
  padding: 0 6px;
  line-height: 20px;
  text-align: center;
  background: #eef1f5;
  border-radius: 3px;
  font-size: 12px;
  color: #5a739a;
  margin-right: 4px;
  margin-bottom: 4px;
}
.model-tag-wrap {
  display: flex;
  flex-wrap: wrap;
}
.model-tag + .model-tag {
  margin-left: 4px;
}
</style>
